package com.zxshhy.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: zxs
 * @Date: 2023/08/26
 * @Description:  线程池配置
 */

@Slf4j
@Configuration
public class TaskExecutePool {

    /**
     * 二阶段协议分布式事务
     * @return
     */
    @Bean("seataTaskPool")
    public ThreadPoolTaskExecutor timeTaskExecutePool(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("seataTask");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
//
//    /**
//     * 会员批量操作线程池
//     * @return
//     */
//    @Bean("batchJobPool")
//    public ThreadPoolTaskExecutor batchJobExecutePool(){
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(1);
//        executor.setMaxPoolSize(1);
//        executor.setQueueCapacity(200);
//        executor.setThreadNamePrefix("BatchJob");
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//        executor.initialize();
//        return executor;
//    }
//
//    /**
//     * 默认线程池
//     * @return
//     */
//    @Bean("taskExecutor")
//    public ThreadPoolTaskExecutor defaultExecutor(){
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(4);
//        executor.setMaxPoolSize(10);
//        executor.setQueueCapacity(1000);
//        executor.setThreadNamePrefix("DefaultTaskExecutor");
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        executor.initialize();
//        return executor;
//    }

    @Bean
    public AsyncUncaughtExceptionHandler asyncUncaughtExceptionHandler(){
        return (throwable,method,objects) -> log.error("Exception in async method:{},message:{}",method.getName(),throwable.getMessage());
    }
}
